#ifndef __uart_kenny_dkfjiwoo3w3__
#define __uart_kenny_dkfjiwoo3w3__

#include <hude/utils/serialport.hpp>

#include "brick/brick.hpp"

namespace ha
{
    namespace brick
    {
        /*********************************************************************
         * @brief 真实串口
         */
        class uart_t :
            public _brick_aio_t< uart_t >
        {
        public:
            uart_t( aio_t aio, const json_t& args ) : _brick_aio_t< uart_t >( aio )
            {
                if( this->settings( args ) )
                {
                    this->mount( uart_.native() );
                }
            }

            ~uart_t()
            {
                this->unmount( uart_.native() );
            }

            int recv( void* p, size_t n ) { return uart_.recv( p, n ); }

            int send( const void* p, size_t n ) override { return uart_.send( p, n ); }

            void close() override { uart_.close(); }

            bool settings( const json_t& args ) override;

            const std::string& name() const { return name_; }

        private:
            std::string               name_;
            hude::utils::serialport_t uart_;
        };

        /*********************************************************************
         * @brief 设置参数
         */
        inline bool uart_t::settings( const json_t& args )
        {
            auto name = hude::utils::json_path_t::value< std::string >( args, "name" );

            if( ! name )
            {
                llog_err( "<brick>", "ERROR: Not uart name" );

                return false;
            }

            name_ = *name;

            if( ! uart_.open( name_.c_str(), false ) )
            {
                llog_err( "<brick>", "ERROR: open uart: %s", name_.c_str() );

                return false;
            }

            {
                auto baud = hude::utils::json_path_t::value_or_default< int >( args, 115200, "baud" );
                auto bits = hude::utils::json_path_t::value_or_default< int >( args, 8, "bits" );
                auto stop = hude::utils::json_path_t::value_or_default< int >( args, 0, "stop" );

                auto ret = uart_.settings( baud, 1, bits, stop, 0 );

                if( ! ret )
                {
                    llog_err( "<brick>", "ERROR: settings uart: %s", name_.c_str() );

                    uart_.close();

                    return false;
                }
            }

            llog_nte( "<brick>", "\t SUCCESS: <brick> uart( handle: %d, name: %s )", uart_.native(), name_.c_str() );

            return true;
        }

    } //namespace brick
} //namespace ha

#endif //__uart_kenny_dkfjiwoo3w3__

